<?php
namespace pft\Member\dt;
use pft\notice;

class MemberAccount_dt{
    const MEM_TABLE = 'pft_member';
    const MOBILE = 'mobile';
    const ACCOUNT = 'account';
    const CHK_MODE_STRICT = 1;

    const ADMINID = 4;
	//会员类型0供应商1分销商2直接供应方5普通用户6员工7集团帐号9平台帐号
    const APPLYER = 0;
    const BUYER = 1;
    const PROVIDER = 2;
    const NORMAL = 5;
    const STUFF = 6;
    const COMPANY = 7;

    const RELATION_REMOVE = 1;
    const RELATION_REBUILD = 2;

    const SALE_APPLY = 1;
    const TAO_APPLY = 2;

    private $db;
    private $did;
    private $soap = null;
    public function __construct($db, $did=0, \SoapClient $soap=null)
    {
        $this->db = $db;
        if(!empty($did)) {
            $this->did = $did;
        }
        if(!is_null($soap)) {
            $this->soap = $soap;
        }
    }

    /**
     * 会员登录
     * @param $account
     * @param $pwd
     * @return array
     */
    public function Login($account, $pwd)
    {
        $sql = "SELECT id,dname,cname,password,dtype,derror,status,errortime FROM ".
            self::MEM_TABLE." WHERE status IN(0,3) AND ";
        if(ismobile($account)) {
            $sql .= " mobile='$account'";
        }
        else {
            $sql .= " account='$account'";
        }
        $sql .= ' LIMIT 1';
        $this->db->query($sql);
        $res = $this->db->fetch_assoc();
        $derror = $res['derror'];
        if($res) {
            $encode_pwd = md5($pwd);
            if($res['password']!=$encode_pwd) {
                $sql_up = "UPDATE pft_member set derror=derror+1".
                    ($derror==5? ',errortime=now()':'').
                    " WHERE id={$res['id']} limit 1";
                $this->db->query($sql_up);
                return array(
                    'status' => 'fail',
                    'msg'    => '登录失败,账号不存在或密码错误'
                );
            }
            $sql_up="update pft_member set lasttime=now(),derror=0,errortime=''".
                "where id={$res['id']}";
            $this->db->query($sql_up);
            return array(
                'status' => 'ok',
                'msg'    => '登录成功',
                'body'   => $res
            );
        }
        return array(
            'status' => 'fail',
            'msg'    => '登录失败,账号不存在或密码错误'
        );
    }


    /**
     * 会员注册
     *
     * @param array $mainData 会员主表数据（字段参考表结构）
     * @param array $extData  会员扩展表数据（字段参考表结构）
     * @param int $parent_id 父ID，添加员工时必须
     * @return array|int
     * @throws \InvalidArgumentException
	 * @editor Tongbc
	 * 手机端注册不传 dname，新增第四个默认参数，true时不检测 dname 字段
     */
    public function register($mainData, $extData=array(), $parent_id=0)
    {
		
        if($mainData['dtype']==self::STUFF && !$parent_id) {
            throw new \InvalidArgumentException('员工身份上级ID不能为空！');
        }
        $result = $this->registerMember($mainData);
        if($result['status']!='ok') {
            return $result;
        }
        if($mainData['dtype']==6) {
            //员工，添加从属关系
            $lastid = explode('|', $result['body']);
            try{
                $res_reltion = $this->createRelationship($parent_id, $lastid[0] , 2, 1);
                if($res_reltion['status']!='ok') {
                    $rm_stuff = "DELETE FROM pft_member WHERE id={$result['body']}";
                    $this->db->query($rm_stuff);
                    return $res_reltion;
                }
            } catch(\Exception $e) {
                echo $e->getMessage();
            }
        }
        $fid = explode('|', $result['body']);
        $extData['fid'] = $fid[0];
        $exRes = $this->createMemberInfo($extData);
        if($exRes['status']=='ok') {
            return $result;
        }
        return $exRes;
    }

    /**
     * 会员信息更新
     *
     * @param int $mid 会员ID
     * @param array $mainData 主表数据
     * @param array $extData  扩展表数据
     * @return array
     */
    public function update($mid,Array $mainData=array(), Array $extData=array())
    {
        if(!$mid || !ctype_digit($mid)) {
            return array('status'=>'fail', 'msg'=>'会员ID格式错误！');
        }

        if(!empty($mainData)) {
            $r1 = $this->updateMember($mainData, $mid);
            if($r1['status']!='ok') {
                return $r1;
            }
        }

        if(!empty($extData) ) {
            $r2 = $this->updateMemberInfo($extData, $mid);
            if(!$r2) return array('status'=>'fail', 'msg'=>'更新会员扩展信息失败');
        }
        return  array('status'=>'ok', 'msg'=>'更新成功','body'=>$mid);
    }

    /**
     * 生成会员维一登录账户
     *
     * @param $dtype 账户类型 0供应商1分销商2直接供应方5普通用户6员工7集团帐号9平台帐号
     * @return string
     */
    private function _generateAccount($dtype)
    {
        $account_need = array(0=>100000,1=>200000,2=>600000,7=>1000);
        if(!array_key_exists($dtype, $account_need)) return '';
        $str = "SELECT MAX(account)+1 as passport FROM pft_member".
            " WHERE 1=1";
        $where = '';
        if($dtype==0) {
            //供应商
            $where .= " AND account BETWEEN 100000 AND 199999";
        }
        else if($dtype==1) {
            //分销商
            $where .= " AND account BETWEEN 200000 AND 599999";
        }
        else if($dtype==2) {
            //直接供应方
            $where .= " AND account BETWEEN 600000 AND 999999";
        }
        else if($dtype==7) {
            //集团
            $where .= " AND account BETWEEN 1000 AND 9999";
        }
        else {
            $where .= " AND dtype={$dtype}";
        }
        $where .= " AND account NOT IN('test','test1')";
        $this->db->query($str.$where);
        $this->db->fetch_assoc();
        $ret = !is_null($this->db->f('passport')) ? $this->db->f('passport'): $account_need[$dtype];
        return $ret;
    }
    /**
     * 会员注册,如果是注册直接供应商，不检测手机号
     *
     * @param $params
     * @return int
	 * @editor Tongbc
	 * 新增参数二，true 时为手机端注册，只检测手机号不检测 dname
     */
    public function registerMember($params)
    {
        if($params['dtype']!=2) {
			$mobile = isset($params['mobile']) ? $params['mobile'] : '';
			$ret=$this->chkDname($params['dname'],$mobile);
			if($ret) {
				$uid = array_keys($ret);
				return array(
					'status'=>'fail',
					'msg'   => "{$params['dname']}已存在",
					'body'  => 'username|'.$uid[0],
				);
			}
			if( $params['mobile']!='' && $this->chkPassport($params['mobile']) ) {
				return array(
					'status'=>'fail','body' => 'mobile|'.$params['mobile'],
					'msg'   => "手机号{$params['mobile']}已存在"
				);
			}

        }

        if($params['dtype']==5) {
            $params['account'] = $params['mobile'];
		}elseif($params['dtype']==6) {
            if(is_numeric($params['account'])) {
                return array(
                    'status'=>'fail',
                    'msg'   => "员工帐号必须为字母加数字组合已存在！",
                    'body'  => 'account'
                );
            }
            $len = strlen($params['account']);
            if($len<4 || $len>12 || !ctype_alnum($params['account'])) {
                return array(
                    'status'=>'fail',
                    'msg'   => "员工帐号为4位~12位英文或数字",
                    'body'  => 'account'
                );
            }
            $sql_chk = "select id from pft_member where account='{$params['account']}' LIMIT 1";
            $this->db->query($sql_chk);
            $this->db->fetch_assoc();
            if($this->db->f('id')>0) {
                return array(
                    'status'=>'fail',
                    'msg'   => "员工帐号‘{$params['account']}’已存在！",
                    'body'  => 'account'
                );
            }
            $params['member_auth'] = 'pro,order,orderAlter,low,file,ps,notice';
        }
        else {
            $params['account'] = $this->_generateAccount($params['dtype']);
        }
        $params['headphoto'] = 'images/touxiang.png';//默认头像
        $params['creattime'] = date('Y-m-d H:i:s');
        $str = sqlInsert('pft_member', $params);
//        $str = sqlUpdate('pft_member', $params,'id='.$last_insertid);
        $this->db->query($str);
        $msg = '保存成功';
        if($params['dtype']>5) {
            $msg .= "，登录账号为【{$params['account']}】";
        }
        return array(
            'status'=>'ok',
            'msg'   => $msg,
            'body'  => mysql_insert_id().'|'.$params['account']
        );
    }

    /**
     * 会员注册扩展表信息
     *
     * @param $params 会员扩展表数据（字段参考表结构）
     * @return array
     */
    public function createMemberInfo($params)
    {
        $params['bsn_les']  = 'images/other/noimg.jpg';
        $params['opt_les']  = 'images/other/noimg.jpg';
        $params['auth_les'] = 'images/other/noimg.jpg';
        $params['id_card']  = 'images/other/noimg.jpg';
        $str = sqlInsert('pft_member_extinfo', $params);
        if($this->db->query($str)) {
            $last_insertid = mysql_insert_id();
            return array(
                'status'=>'ok',
                'msg'   => '保存成功',
                'body'  => $last_insertid
            );
        }
        return array(
            'status'=>'fail',
            'msg'   => '会员扩展信息保存失败',
            'body'  => 'sql错误'
        );
    }

    /**
     * 检测会员状态为正常（0）或禁用（1）的数据是否已经存在
     *
     * @param array $params 检查条件
     * @param $id 排除的ID
     * @return mixed
     */
    public function ChkExist(Array $params, $id)
    {
        $str_chk = "SELECT COUNT(*) AS c FROM pft_member WHERE status<>2 AND dtype<2";
        foreach($params as $colm=>$val) {
            $str_chk .= " AND `$colm`='{$val}'";
        }
        $str_chk .=" AND id<>$id";
        $this->db->query($str_chk);
        $this->db->fetch_assoc();
        return $this->db->f('c');
    }

    /**
     * 更新会员主表信息（手机号唯一、企业名称唯一）
     *
     * @param $params 主表数据
     * @param $id
     * @return array
     */
    public function updateMember($params, $id)
    {
        if(!empty($params['mobile'])) {
            if($this->ChkExist(array('mobile'=>$params['mobile']), $id)>0) {
                return array(
                    'status'=>'fail',
                    'msg'   => '更新失败，手机号' .$params['mobile'].'已存在',
                );
            }
        }
        if(isset($params['dname'])) {
            if($this->ChkExist(array('dname'=>$params['dname']), $id)>0) {
                return array(
                    'status'=>'fail',
                    'msg'   => '更新失败，企业' .$params['dname'].'已存在',
                );
            }
        }

        $sql = sqlUpdate('pft_member', $params,'id='.$id);
        $this->db->query($sql);
        return array(
            'status'=>'ok',
            'msg'   => '更新成功',
        );

    }

    /**
     * 更新会员信息扩展表
     *
     * @param $params（参考表中的字段）
     * @param $fid 会员表ID
     * @return mixed
     */
    public function updateMemberInfo($params, $fid)
    {
        $sql = sqlUpdate('pft_member_extinfo', $params,'fid='.$fid);
        return $this->db->query($sql);
    }

    /**
     * 获取6位登录账户
     *
     * @param $mid 会员ID
     * @return mixed
     */
    public function getAccountById($mid) {
        $str = "SELECT account FROM pft_member WHERE id=$mid";
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('account');
    }

    /**
     * 获取会员表的公司名称
     *
     * @param $mid 会员ID
     * @return mixed
     */
    public function getNameById($mid) {
        $str = "SELECT dname FROM pft_member WHERE id=$mid";
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('dname');
    }

    /**
     * 检测会员关系是否已经建立
     * @param $parent_id
     * @param $son_id
     * @return mixed
     */
    public function chkRelationship($parent_id, $son_id)
    {
        $str_chk = "SELECT id,status FROM pft_member_relationship WHERE ".
            "parent_id={$parent_id} AND son_id={$son_id} LIMIT 1";
        $this->db->query($str_chk);
        return $this->db->fetch_assoc();
    }

    /**
     * 供应商、分销商、员工建立关系
     *
     * @param $parent_id 上级ID
     * @param $son_id    下级ID
     * @param int $son_id_type 0分销商1资源方2员工3供应商(父ID为集团帐号情况下)
     * @param int $ship_type 关系类型0供销关系1从属关系2平级关系3推荐关系
     * @param string $account 6位数账号可为空
     * @return array
     * @throws \InvalidArgumentException
     */
    public function createRelationship($parent_id, $son_id, $son_id_type=0,
                                       $ship_type=0, $account='')
    {
        //检查供应商是否属于某个集团
        if($ship_type==0) {
            $sql_chk = "SELECT parent_id FROM pft_member_relationship WHERE".
                " son_id_type=3 AND son_id=$parent_id AND ship_type=1";
            $this->db->query($sql_chk);
            $this->db->fetch_assoc();
            //将分销商加入到集团账户
            if( $this->db->f('parent_id') > 0) {
                $company_id = $this->db->f('parent_id');
                $this->_createRelationship($company_id, $son_id, 0, 1);
            }
        }
        return $this->_createRelationship($parent_id, $son_id, $son_id_type,
            $ship_type, $account);
    }

    private function _createRelationship($parent_id, $son_id, $son_id_type=0,
                                      $ship_type=0, $account='')
    {
        $son_type_list = array('分销商','资源方','员工','供应商');
        if(!is_numeric($parent_id) || !$parent_id) {
            throw new \InvalidArgumentException('$parent_id必须为大于0的数字');
        }
        $ret = $this->chkRelationship($parent_id, $son_id);
        if($ret['id']) {
            if($ret['status']==1) {
                return $this->RelationHanler(self::RELATION_REBUILD,
                    $parent_id, $son_id);
            }
            else {
                return array(
                    'status'=>'fail',
                    'msg'   => $son_type_list[$son_id_type].'已经添加，请勿重复添加',
                    'body'  => ''
                );
            }
        }
        //检测供应商是否已加入其他集团
        if($son_id_type==3 && $ship_type==1) {
            $this->db->query("SELECT id FROM pft_member_relationship WHERE son_id={$son_id} AND son_id_type=3 AND ship_type=1 AND status=0");
            $this->db->fetch_assoc();
            if($this->db->f('id')>0) {
                return array(
                    'status'=>'fail',
                    'msg'   => '该供应商已经加入其他集团，请勿重复添加',
                    'body'  => ''
                );
            }
        }
        $str = "INSERT INTO pft_member_relationship(parent_id,son_id,son_id_type"
            .",ship_type,rectime) VALUES({$parent_id},{$son_id},{$son_id_type},"
            ."{$ship_type},now())";
//        echo $str;
        $this->db->query($str);
        //当供应商与分销商建立关系时往分销商产品销售表,pids=''。——sayed by KH
        if($son_id_type==0) {
            $str_sale = "INSERT INTO pft_product_sale_list(fid,aid,pids) "
                ."VALUES($son_id,$parent_id,'')";
            $this->db->query($str_sale);
        }
        $msg = $son_type_list[$son_id_type].'添加成功';
        if(!empty($account)) {
            $msg .= ',登录账号为【'. $account.'】或您设置的手机号';
        }
        return array(
            'status'=>'ok',
            'msg'   => $msg,
            'body'  => mysql_insert_id()
        );
    }
    /**
     * 合作关系操作
     * @param $action 操作类型  解除：MemberAccount::RELATION_REMOVE，
     *                          重建：MemberAccount::RELATION_REBUILD
     * @param $parent_id 父id
     * @param $son_id 子id
     * @param int $ship_type 关系类型[0供销关系1从属关系2平级关系3推荐关系],
     *                          （若为“供销关系”，需更新sale_list表）
     * @return array  成功array('status'=>'ok','msg'   => '关系解除成功',
     */
    public function RelationHanler($action, $parent_id, $son_id, $ship_type=0)
    {
        switch($action) {
            case self::RELATION_REMOVE:
                $status = 1;
                $op_time = 'cuttime=now()';
                break;
            case self::RELATION_REBUILD:
                $op_time = 'restoretime=now()';
                $status = 0;
                break;
        }
        $res = $this->_RelationHanler($parent_id, $son_id, $ship_type,
            $status, $op_time);
        return $res;
    }

    /**
     * 获取会员直接的关系
     *
     * @param integer $parent_id
     * @param integer $son_id
     * @return mixed
     */
    public function GetReletion($parent_id, $son_id)
    {
        $sql = "SELECT son_id_type,ship_type,status FROM ".
            "pft_member_relationship WHERE parent_id=$parent_id ".
            "AND son_id=$son_id LIMIT 1";
        $this->db->query($sql);
        return $this->db->fetch_assoc();
    }

    private function _RelationHanler($parent_id, $son_id, $ship_type,
                                     $status, $op_time)
    {
        $msg = $status == 1 ? '删除' : '添加';
        $sql = "UPDATE pft_member_relationship SET status=$status,$op_time "
            ."WHERE parent_id=$parent_id AND son_id=$son_id LIMIT 1";
        if($this->db->query($sql)){
            if($status==1) {
                //如果是删除供销关系，那么要将转供应的产品表中的数据删除
                //TODO:1.获取这个供应商给分销商转供应的产品ID
                $sql_get_pid = "SELECT pid FROM pft_p_apply_evolute WHERE sid=$parent_id AND fid=$son_id";
                $this->db->query($sql_get_pid);
                $rm_pids = array();
                while($p = $this->db->fetch_assoc()) {
                    $rm_pids[] = $p['pid'];
                }
                if(count($rm_pids)>0) {
                    //TODO:2删除分销商转供应出去的产品数据（3手）
                    $sql_rm_children = "DELETE FROM pft_p_apply_evolute WHERE pid IN (" . implode(',', $rm_pids) .") AND sid=$son_id";
                    //TODO:3删除该供应商转给改分销商的数据（2手）
                    $sql_rm_parent   = "DELETE FROM pft_p_apply_evolute WHERE sid=$parent_id AND fid=$son_id";
                    $this->db->query($sql_rm_children);
                    $this->db->query($sql_rm_parent);
                }

            }

            if($ship_type==0) {
                $sql_sale_list = "UPDATE pft_product_sale_list SET status=$status"
                    . " WHERE aid=$parent_id AND fid=$son_id LIMIT 1";
                $this->db->query($sql_sale_list);
            }
            elseif($ship_type==1) {
                $rlp = $this->GetReletion($parent_id, $son_id);
                //如果是员工关系，将会员表状态改为删除
                if($rlp['son_id_type']==2)
                {
                    $this->StatusSet($son_id, 2, true);
                }
            }
            return  array(
                'status'=>'ok',
                'msg'   => $msg.'成功',
                'body'  => $parent_id .'|'. $son_id
            );
        }
        return array(
            'status'=>'fail',
            'msg'   => $msg.'失败',
            'body'  => mysql_error()
        );
    }
    /**
     * 获取会员列表
     *
     * @param $params 查询条件（参考会员表中的字段）
     * @param bool $count 是否统计
     * @return array
     * @throws \InvalidArgumentException
     */
    public function getMemList($params, $count=false)
    {
        if(!is_array($params) || empty($params)) {
            throw new \InvalidArgumentException("Wrong dataType of params");
        }
        $where = '';
        if(!empty($params['dname'])) {
            $where .= " AND m.dname LIKE '%{$params['dname']}%'";
        }
        if(!empty($params['cname'])) {
            $where .= " AND m.cname LIKE '%{$params['cname']}%'";
        }
        if(isset($params['id']) && is_numeric($params['id'])) {
            $where .= " AND m.id='{$params['id']}'";
        }
        if(!empty($params['alipay'])) {
            $where .= " AND m.alipay='{$params['alipay']}'";
        }
        if(isset($params['dtype'])) {
            $where .= " AND m.dtype IN({$params['dtype']})";
        }
        if(isset($params['status'])) {
            $where .= " AND m.status={$params['status']}";
        }
        else {
            $where .= " AND m.status IN(0,3)";
        }
        if(!empty($params['dcode'])) {
            $where .= " AND m.dcode='{$params['dcode']}'";
        }
        if(!empty($params['bt1']) && !empty($params['et1'])) {
            $where .= " AND m.creattime BETWEEN '{$params['bt1']}' AND '{$params['et1']}'";
        }
        $where .= empty($params['mobile']) ? '' : " AND m.mobile='{$params['mobile']}'";
        $where .= empty($params['account']) ? '':" AND m.account='{$params['account']}'";
//        ,e.add_saler_type
        if(!$count) {
            $sql = <<<SQL
            SELECT m.id, m.dtype, m.account, m.dname, m.status,
            m.mobile, m.creattime, m.lasttime, m.cname,m.mlevel,
            m.dcode, m.alipay, m.pay_on_order,m.status,m.n_send,
            e.id as eid,e.fid, e.position, e.sex, e.email, e.com_name,e.coop,
            e.short_company_name, e.com_type, e.province, e.city,e.add_saler_type
            FROM pft_member m,pft_member_extinfo e
            WHERE m.id=e.fid
            {$where}
            ORDER BY m.status DESC, m.id DESC
            LIMIT {$params['limit']}, {$params['offset']}
SQL;
        }
        else {
            $sql = <<<SQL
            SELECT COUNT(*) AS total FROM pft_member m,pft_member_extinfo e
            WHERE m.id=e.fid
            {$where}
SQL;
            $this->db->query($sql);
            $this->db->fetch_assoc();
            return $this->db->f('total');
        }
        $this->db->query($sql);
        $list = array();
        while($l = $this->db->fetch_assoc()) {
            $list[] = $l;
        }
        return $list;
    }

    public function getMemName($mids)
    {
        if(!$mids) return false;
        $mids = is_array($mids) ? implode(',', $mids) : abs($mids);
        $sql = "SELECT id,dname,getPY(dname,1) as py FROM pft_member WHERE id IN($mids) ORDER BY py ASC";
        $this->db->query($sql);
        $names = array();
        while($name=$this->db->fetch_assoc()) {
            $names[$name['id']] = $name['py'].'-'. $name['dname'];
        }
        return $names;
    }
    /**
     * 查看单个会员的关系列表
     *
     * @param integer $id 会员ID
     * @param int $type 0供应商1分销商2资源方
     * @param $memDtype
     * @return array
     */
    public function gemMemRShip($id, $type=1, $memDtype=-1)
    {
        $str = <<<SQL
 SELECT r1.id, r1.parent_id,r1.son_id,r1.son_id_type,r1.ship_type,r1.status,r1.rectime,
  m1.id as mid,m1.dname ,m1.cname,m1.dtype,m1.account,m1.mobile
  FROM pft_member_relationship r1
  LEFT JOIN pft_member m1
SQL;
        if($type==0) {
            $str .= " ON m1.id=r1.parent_id WHERE r1.son_id = $id AND r1.son_id_type=0";
        }
        elseif($type==1) {
            $str .= " ON m1.id=r1.son_id WHERE r1.parent_id = $id AND r1.son_id_type=0";
        }
        elseif($type==2) {
            $str .= " ON m1.id=r1.son_id WHERE r1.parent_id = $id AND r1.son_id_type=1";
        }
        elseif($type==3) {
            $str .= " ON m1.id=r1.son_id WHERE r1.parent_id = $id";
        }
        if($memDtype>-1) {
            $str .= " AND m1.dtype={$memDtype}";
        }
        $str .= " ORDER BY r1.status ASC,r1.id ASC";
        $this->db->query($str);
        $list = array();
        while($l = $this->db->fetch_assoc()) {
            $list[] = $l;
        }
        return $list;
    }

    /**
     * 验证用户账号是否存在
     *
     * @param string $passport
     * @return mixed
     */
    public function chkPassport($passport)
    {
        // $p_type = ismobile($passport) ? self::MOBILE : self::ACCOUNT;
        // $str = "SELECT mobile FROM pft_member WHERE "
            // . $p_type ."='{$passport}' AND (status=0 OR status=3)  LIMIT 1";
        // $this->db->query($str);
        // $this->db->fetch_assoc();
        // return $this->db->f('mobile');
		$p_type = ismobile($passport) ? self::MOBILE : self::ACCOUNT;
        $str = "SELECT * FROM pft_member WHERE "
            . $p_type ."='{$passport}' AND (status=0 OR status=3)  LIMIT 1";
        $this->db->query($str);
        // print_r($this->db->fetch_assoc());
		// exit;
        return $this->db->fetch_assoc();
    }

    /**
     * 根据分销商名称获取、检测已存在的分销商
     *
     * @param STRING $name 公司名称
     * @param INT $mode 值为'strict'模式时进行严格检测
     * @param INT $dtype 会员类型
     * @return array
	 * @editor TongBC
	 * 新增参数2，分销商名称可能为空，导致多条数据，手机端注册分销商名称是空的
     */
    public function chkDname($name,$mobile='')
    {
        $str = "SELECT id, dname FROM pft_member WHERE dname='$name' AND status=0";
		if($mobile) $str.=' AND mobile='.$mobile;
		$str.=' LIMIT 1';
        $this->db->query($str);
        $mem_list = array();
        while($r=$this->db->fetch_assoc()) {
            if(!$r['id']) break;
            $mem_list[$r['id']] = $r['dname'];
        }
        return $mem_list;
    }

    /**
     * 分销商模糊查找
     *
     * @param string $name 企业名称
     * @param string $dtype 会员类型（字符串逗号分隔）
     * @param int $aid 供应商ID
     * @param null $com_type 企业类型
     * @return array
     */
    public function SearchDistor($name ,$dtype='0,1', $aid=0,$com_type=null,$limit='')
    {
        $created = $this->GetRelation($aid);
		// echo $created.'++++++++';
		// print_r($created);
		// exit;w
        $str = "SELECT m.id, m.dname,m.mobile,m.account as passport, m.cname,e.com_type"
            ." FROM pft_member m,pft_member_extinfo e "
            ." WHERE e.fid=m.id AND m.id<> $aid AND m.dname LIKE '%$name%'"
            . " AND m.dtype IN({$dtype}) AND m.status=0 AND e.com_type<>'景区'";
        //搜索电话
		if($search_type){
			$str = "SELECT m.id, m.dname,m.mobile,m.account as passport, m.cname,e.com_type"
            ." FROM pft_member m,pft_member_extinfo e "
            ." WHERE e.fid=m.id AND m.id<> $aid AND m.mobile='$name'"
            . " AND m.dtype IN({$dtype}) AND m.status=0 AND e.com_type<>'景区'";
		}
		if(!is_null($com_type)) {
            $str .= " AND e.com_type IN($com_type)";
        }
		if($limit!='')
			$str .=" LIMIT $limit";
        // echo $str;
	    // exit;
        $this->db->query($str);
        $ls = array();
        while($r=$this->db->fetch_assoc()) {
            $r['created'] = in_array($r['id'], $created) ? 1 : 0;
            $ls[] = $r;
        }
        return $ls;
    }

	public function _SearchDistor($name ,$dtype='0,1', $aid=0,$com_type=null,$search_type=null)
    {
        $created = $this->GetRelation($aid);
        $str = "SELECT m.id, m.dname,m.mobile,m.account as passport, m.cname,e.com_type"
            ." FROM pft_member m,pft_member_extinfo e "
            ." WHERE e.fid=m.id AND m.id<> $aid AND m.dname='$name'"
            . " AND m.dtype IN({$dtype}) AND m.status=0 AND e.com_type<>'景区'";
		if(!is_null($com_type)) {
            $str .= " AND e.com_type IN($com_type)";
        }
        $this->db->query($str);
        $ls = array();
        while($r=$this->db->fetch_assoc()) {
            $r['created'] = in_array($r['id'], $created) ? 1 : 0;
            $ls[] = $r;
        }
        return $ls;
    }

    /**
     * 根据供应商或分销商ID获取关系列表数据
     *
     * @param $aid
     * @return array
     */
    public function GetRelation($aid)
    {
        $sql = "SELECT son_id FROM pft_member_relationship "
            ."WHERE parent_id=$aid AND status=0";
        $this->db->query($sql);
        $did = array();
        while($r=$this->db->fetch_assoc()) {
            $did[] = $r['son_id'];
        }
        return $did;
    }

    /**
     * 重置密码
     *
     * @param $passport 6位数账号或11位手机号
     * @param $password 密码
     * @return mixed
     */
    public function resetPassword($passport, $password)
    {
        $p_type = ismobile($passport) ? self::MOBILE : self::ACCOUNT;
        $chk_exist = $this->chkPassport($passport);
        if($chk_exist){
            $password = md5(md5($password));
            $str = "UPDATE ".self::MEM_TABLE." SET password='{$password}',derror=0"
                .",errortime='' WHERE {$p_type}='{$passport}' AND status=0 LIMIT 1";
            return $this->db->query($str);
        }
        return false;
    }

    /**
     * 发送验证码
     *
     * @param $mobile
     * @param $tpl 短信模板（参考tpl/sms目录下的文件）
     * @param \SoapClient $soap
     * @return mixed
     */
    public static function sendVcode($mobile, $tpl, \SoapClient $soap)
    {
        $_SESSION['vcode'] = genRandomString(6);
        $_SESSION['timer'] = $_SERVER['REQUEST_TIME'];

        $search = array('{vcode}');
        $replace = array($_SESSION['vcode']);
        $content = str_replace($search,$replace, $tpl);
        $r = $soap->Send_SMS_G($mobile,$content);
        return $r;
    }

    /**
     * 获取几种费用（由管理员配置）
     *
     * @return mixed
     */
    public function GetFeesCfg()
    {
        $sql = "SELECT fee_platform,fee_bank,fee_sms FROM " .self::MEM_TABLE
            ." WHERE id={$this->did}";
        $this->db->query($sql);
        return $this->db->fetch_assoc();
    }

    /**
     * 统计供应商发送通知接收的人数
     *
     * @param int $son_id_type
     * @param bool $countTotal
     * @param bool $byadmin 如果为true则统计平台所有会员
     * @return mixed
     */
    public function GetDistorByApplyerId($son_id_type=0,
                                         $countTotal=false, $byadmin=false)
    {
        if($byadmin) {
            $sql = "SELECT COUNT(*) AS c FROM pft_member WHERE status=0 AND mobile<>''";
            $this->db->query($sql);
            $this->db->fetch_assoc();
            return $this->db->f('c');
        }

        $str = <<<SQL
        FROM pft_member_relationship f
        LEFT JOIN pft_member m
        ON f.son_id = m.id
        WHERE f.parent_id={$this->did}
        AND f.son_id_type={$son_id_type}
        AND f.status=0
        AND m.status=0 AND m.mobile <> ''
SQL;
        if($countTotal) {
            $sql = " SELECT COUNT(*) AS c " . $str;
            $this->db->query($sql);
            $this->db->fetch_assoc();
            return $this->db->f('c');
        }
        else {
            $sql = " SELECT m.mobile,m.id ". $str;
        }
//        echo $sql;
        $this->db->query($sql);
        while( $r = $this->db->fetch_assoc()) {
            $distor[$r['id']] = $r['mobile'];
        }
        return $distor;
    }

    /**
     * 查询资金账户余额（参考票付通接口文档——资金余额查看）
     *
     * @param $uid 会员ID
     * @param \SoapClient $soap
     * @param int $dtype 类型0账户余额1可用供应商余额2信用额度，供应商ID类型>0时必填
     * @return mixed
     */
    public function ShowBalance($uid=0, \SoapClient $soap=null, $dtype=0)
    {
        if(is_null($soap)) {
            $soap = $this->soap;
        }
        if(!$uid) {
            $uid = $this->did;
        }
        $xml = $soap->PFT_Member_Fund($uid, $dtype);
        $arr = simplexml_load_string($xml);
        return $arr->Rec->UUamoney;
    }

    /**
     * 根据会员ID获取详细信息
     *
     * @param $mid 会员ID
     * @return mixed
     */
    public function GetOne($mid)
    {
        $sql = <<<SQL
        SELECT m.id,m.dtype, m.account, m.dname, m.status, m.address,
         m.mobile, m.qq, m.creattime, m.lasttime, m.headphoto, m.cname,
         m.ctel, m.smstype, m.smsauto, m.alipay, m.pay_on_order, m.n_accept,
         m.fee_platform, m.fee_bank, m.fee_sms,
         e.fid, e.position, e.sex, e.email, e.com_name,e.short_company_name,
         e.com_type, e.province, e.city, e.fax,e.website, e.business,
         e.license_no,e.bsn_les,e.opt_les,e.auth_les, e.id_card,e.add_saler_type
         FROM pft_member m
         LEFT JOIN pft_member_extinfo e ON m.id=e.fid
         WHERE m.id=$mid
SQL;
        $this->db->query($sql);
        return $this->db->fetch_assoc();
    }

    /**
     * 获取会员手机号
     *
     * @param mixed $uid 会员ID
     * @return array ID=>手机号
     */
    public function GetMobileWithId($uid)
    {
        $ql = "SELECT id,mobile FROM pft_member WHERE ";
        if(is_numeric($uid)) {
            $ql .= " id=$uid";
        }
        elseif(strpos($uid,',')!==false) {
            $ql .= " id IN($uid)";
        }
//        echo $ql;
        $ret = array();
        $this->db->query($ql);
        while($r=$this->db->fetch_assoc()) {
            $ret[$r['id']] = $r['mobile'];
        }
        return $ret;
    }

    /**
     * 查找直接供应商
     *
     * @param $sname 直接供应商名字
     * @return array
     */
    public function GetSalerList($sname=null)
    {
        $str = "SELECT m.id, m.dname FROM pft_member m "
            . " LEFT JOIN uu_land l ON l.salerid=m.account WHERE"
            . " m.dtype=2 AND m.status=0 AND l.status=1";
        if(!empty($sname)) {
            $str .= " AND dname LIKE '%$sname%' ";
        }
        $this->db->query($str);
        $mem_list = array();
        while($r=$this->db->fetch_assoc()) {
            $mem_list[$r['id']] = $r['dname'];
        }
        return $mem_list;
    }

    /**
     * 查询会员的审核、认证状态
     *
     * @param $mid 会员ID
     * @return array
     */
    public function StatusChk($mid)
    {
        $res = $this->GetOne($mid);
        if($res['status']!=0) {
            switch($res['status']){
                case 1:
                    $msg = "账号已被禁用";
                    break;
                case 2:
                    $msg = "账号已被删除";
                    break;
                case 3:
                    $msg = "申请还未通过审核";
                    break;
            }
            return array(
                'status'=>'fail',
                'msg'   => $msg,
                'body'  => 'status'
            );
        }
        if(!$res['alipay']) {
            return array(
                'status'=>'fail',
                'msg'   => '您还未绑定支付宝账号，<a href="account_info.html?b">立即绑定</a>',
                'body'  => 'alipay'
            );
        }
        if(!$res['bsn_les']) {
            return array(
                'status'=>'fail',
                'msg'   => '您还未上传营业执照，<a href="certifi.html">立即上传</a>',
                'body'  => 'verify'
            );
        }
        if(!$res['opt_les']) {
            return array(
                'status'=>'fail',
                'msg'   => '您还未上传经营许可证，<a href="certifi.html">立即上传</a>',
                'body'  => 'verify'
            );
        }
        if(!$res['id_card']) {
            return array(
                'status'=>'fail',
                'msg'   => '您还未上传身份证，<a href="certifi.html">立即上传</a>',
                'body'  => 'verify'
            );
        }
        return array(
            'status'=>'ok',
            'msg'   => '正常',
        );

    }
	public function pftGetCoop(){
		$did= $this->did;
		$sql="SELECT * FROM pft_tb_bind WHERE id2=$did LIMIT 1";
		$this->db->query($sql);
        $mem = array();
        while($r=$this->db->fetch_assoc()) {
            $mem = $r;
        }
		return $mem;
	}
    /**
     * 会员状态设置
     *
     * @param int $mid 会员ID
     * @param int $status 0正常1禁用2删除3未审核
     * @param bool $rm_stuff 是否是删除员工操作
     * @return array
     * @throws \InvalidArgumentException
     */
    public function StatusSet($mid , $status, $rm_stuff=false)
    {
        $LS = array('正常','<span style="color:#F63">禁用</span>',
            '<span style="#F00">删除</span>',
            '<span style="color:#00F">未审核</span>');
        //
        if(!is_numeric($status) || !in_array($status, array_keys($LS))) {
            throw new \InvalidArgumentException('状态错误！');
        }
        if($_SESSION['dtype']==9 || $rm_stuff) {
            $sql = "UPDATE pft_member SET status=$status WHERE id=$mid LIMIT 1";
            $this->db->query($sql);
            return array(
                'status'=> 'ok',
                'msg'   => '设置成功',
                'body'  => $LS[$status]
            );
        }
        else {
            return array(
                'status' => 'fail',
                'msg'    => '只有管理员才可以设置会员状态！'
            );
        }
    }

    /**
     * 获取未通过审核的淘宝分销商申请数据
     *
     * @param $type
     * @return array
     */
    public function GetCoopUnVerify($type=0){
        $status = $type==2 ? 'AND a.status<>2' : "AND a.status={$type}";
        $str = <<<SQL
        SELECT m.account,m.id,m.dname,m.mobile,a.data1,a.creattime
        FROM uu_dist_apply a LEFT JOIN uu_distributor d
        ON a.id2=m.id
        WHERE a.dtype=9 {$status}
        ORDER BY a.creattime DESC,d.id ASC
SQL;
        $this->db->query($str);
        $o = array();
        while($r = $this->db->fetch_assoc()) {
            $o[] = $r;
        }
        return $o;
    }

    /**
     * 获取分销淘宝账号
     *
     * @return mixed
     */
    public function GetCoop() {
        if(!$this->did) return false;
        $str = "SELECT coop FROM pft_member_extinfo WHERE fid=$this->did LIMIT 1";
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('coop');
    }

    /**
     * 获取申请记录列表
     *
     * @param int $dtype 申请类型：1表示分销商申请成为供应商，2表示淘宝码商申请
     * @param int $status
     * @param int $fid
     * @param bool $count
     * @param int $limit
     * @param int $size
     * @return array
     * @throws \InvalidArgumentException
     */
    public function ApplyList($dtype=2,$status=0,$fid=0,$count=false, $limit=0, $size=50)
    {
       if(!is_numeric($dtype) || !is_numeric($status)) {
           throw new \InvalidArgumentException('参数格式错误！');
       }
       if($count) {
            $sql_count = "SELECT COUNT(*) AS c FROM uu_dist_apply l".
                " LEFT JOIN pft_member m ON l.id2=m.id WHERE l.dtype={$dtype}".
                " AND l.status={$status}";
            $this->db->query($sql_count);
            $this->db->fetch_assoc();
            return $this->db->f('c');
        }
        $sql = <<<SQL
        SELECT l.id as log_id,l.id2,l.id3,l.data1,l.data2,l.msg1,
        l.msg2,l.status as verify_status,l.dtype,l.creattime,m.id as uid, m.dtype, m.account,
        m.dname, m.status, m.mobile,m.cname
        FROM uu_dist_apply l LEFT JOIN pft_member m
        ON l.id2=m.id
        WHERE l.dtype={$dtype}
SQL;
        if($status>-1) {
            $sql .= " AND l.status={$status}";
        } else {
            $sql .= " AND l.status<2";
        }
        if($fid>0) {
            $sql .= "AND l.id2=$fid";
        }
        else {
            $sql .= !$status ? ' ORDER BY log_id DESC' : ' ORDER BY log_id ASC';
        }
        $sql .= " LIMIT {$limit},{$size}";
        $this->db->query($sql);
        $ret = array();
        while($r = $this->db->fetch_assoc()) {
            $ret[] = $r;
        }
        return $ret;
    }

    /**
     * 申请(实例化时需传入第二个参数——会员ID)
     * @param $dtype 申请类型:1供应商2淘宝码商
     * @param $data1 申请类型为1时:申请理由；2时:淘宝卖家账号
     * @return mixed
     */
    public function ApplyCreate($dtype, $data1)
    {
        if($dtype==self::TAO_APPLY) {
            $flag = $this->GetCoop();
            if($flag!='') return array('status'=>'fail','msg'=>'账号已绑定或在审核中');
            $data1 = 'tb-t|'. $data1;
            $str = "UPDATE pft_member_extinfo SET coop='$data1' WHERE fid=$this->did LIMIT 1";
            $this->db->query($str);
        }
        elseif($dtype==self::SALE_APPLY) {
            $sql = "SELECT id FROM uu_dist_apply WHERE dtype=".self::SALE_APPLY." AND id2=$this->did AND status<=1";
            $this->db->query($sql);
            $this->db->fetch_assoc();
            if($this->db->f('id')) {
                return array('status'=>'fail','msg'=>'账号已申请或在审核中');
            }
        }
        $str = <<<SQL
INSERT INTO uu_dist_apply(`id2`,`data1`,`dtype`,`creattime`)
VALUES({$this->did},'{$data1}',{$dtype},now())
SQL;
        $this->db->query($str);
        return array('status'=>'ok','msg'=>'申请成功');
    }

    /**
     * 淘宝码商、分销商申请供应商——申请审批操作
     *
     * @param notice $notice 通知类的实例化
     * @param $uid 会员ID
     * @param $log_id 申请记录ID
     * @param $status
     * @param $sms 是否发送短信1发送0不发送
     * @param string $msg 审核信息
     * @param INT $dtype 1供应商申请2淘宝码商申请
     * @return string
     */
    public function ApplyVerify(notice $notice, $uid, $log_id, $status, $sms,
                                $msg='', $dtype=1)
    {
        $n_title = '供应商申请通知';

        if($dtype==2) {
            $n_title = '码商审核通知';
            switch($status) {
                case 1:
                    $coop = "REPLACE(coop,'-t','')";
                    $msg = '您的淘宝码商申请已通过审核！';
                    //$str2 = "UPDATE pft_member_extinfo SET coop=REPLACE(coop,'-t','') WHERE fid=$uid LIMIT 1";
                    break;
                case 2:
                    $coop = '\'\'';
                    $msg = '您的淘宝码商申请未通过审核。理由:' . $msg;
                    break;
                default:
                    $coop = '\'\'';
                    $msg = '您的分销商账号与淘宝账号已解除绑定';
                break;
            }
            $str2 = "UPDATE pft_member_extinfo SET coop=$coop WHERE fid={$uid} LIMIT 1";
//            echo $str2;
            $this->db->query($str2);
        }
        else {
            $msg = $status==1 ? '申请成为供应商审核通过。': $msg;
        }
        $str = <<<SQL
UPDATE uu_dist_apply SET status={$status},`msg1`='{$msg}' WHERE id={$log_id}
SQL;
        if($this->db->query($str)) {
            $res = $notice->AddNotice($n_title, $msg,1,9999,9,
                $sms,'','',$this, $uid);
        }
        if($res['errcode']==1000) {
            if($dtype==1) {
                //变更身份
                $chg_dtype = "UPDATE pft_member SET dtype=0 WHERE id=$uid LIMIT 1";
                $this->db->query($chg_dtype);
            }
            $status='ok';
            $msg   = '已审核';
        } else {
            $status = 'fail';
            $msg    = '发生错误。'. $res['msg'];
        }
        return array('status'=>$status,'msg'=>$msg);
            //$res['errcode']==1000?'ok':$res['msg'];
    }

    /**
     * 获取会员类型，如果是员工身份登录需判断他上级的类型。
     *
     * @param $mid 会员id
     * @return mixed
     */
    public static function GetMemType($mid)
    {
        $sql = "SELECT dtype FROM pft_member WHERE id=$mid";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('dtype');
    }

    /**
     * 员工操作日志
     *
     * @param $fid
     * @param $sid
     * @param $daction
     */
    public static function StuffOptLog($fid, $sid, $daction)
    {
        $sql = "INSERT INTO pft_d_operation_rec(fid,sid,daction,rectime) ".
            "VALUES($fid, $sid,'$daction', NOW())";
        $GLOBALS['le']->query($sql);
    }
    
    /**
     * 设置资金预警阀值
     * @param $mid 会员id
     * @param $threshold 预警金额
     */
    public static function setBankroll($mid,$threshold){
        $sql="update pft_member_extinfo set early_warning=$threshold where fid=$mid limit 1";
        return $GLOBALS['le']->query($sql);
    }
    /**
     * 获取资金预警阀值
     * @param $mid 会员id
     */
    public static function getBankroll($mid){
        $sql="select early_warning from pft_member_extinfo where fid=$mid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('early_warning');
    }
}